package com.heima.comment.service.impl;

import com.heima.comment.service.WmCommentService;
import com.heima.common.exception.CustException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.dtos.CommentManagerDTO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.CommentManagerRepVo;
import com.heima.model.wemedia.vos.CommentManagerVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class WmCommentServiceImpl implements WmCommentService {
    @Autowired
    ArticleFeign articleFeign;
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    WemediaFeign wemediaFeign;

    //自媒体评论管理
    @Override
    public ResponseResult commentManager(CommentManagerDTO dto) {
        //获取当前登录用户
        ApUser wmUser2 = AppThreadLocalUtils.getUser();
        if (wmUser2 == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        Integer wmUserId = wmUser2.getId();

        //查询WmUser
        ResponseResult<WmUser> wmUserResp = wemediaFeign.findById(wmUserId + "");
        if (!wmUserResp.checkCode()) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "当前用户没有开通自媒体账户!");
        }
        WmUser user = wmUserResp.getData();
        //根据apuserId查询作者
        ResponseResult<ApAuthor> apAuthorResp = articleFeign.findByUserId(user.getApUserId());
        if (!apAuthorResp.checkCode()) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "当前用户的作者信息不存在!");
        }
        //获取作者信息
        ApAuthor apAuthor = apAuthorResp.getData();
        //根据作者id查询所有文章列表
        ResponseResult<List<ApArticle>> listResponseResult = articleFeign.articleByAuthorId(apAuthor.getId() + "");
        if (listResponseResult.checkCode()) {
            List<ApArticle> aparticleList = listResponseResult.getData();
            //检查参数
            Integer size = dto.getSize();
            if (size == null || size == 0) {
                size = 5;
            }
            //创建评论集合保存查询到的评论对象
            List<ApComment> apCommentList = new ArrayList<>();
            //根据当前文章查询所有文章的评论,按照时间降序排列,截取前5条
            for (ApArticle apArticle : aparticleList) {
                Query query = Query.query(Criteria.where("articleId").is(apArticle.getId()));
                Sort sort = Sort.by(Sort.Direction.DESC, "creataTime");
                PageRequest page = PageRequest.of(0, size);
                query.with(sort).with(page);
                List<ApComment> apComments = mongoTemplate.find(query, ApComment.class);
                //将查询到的数据添加到集合
                apCommentList.addAll(apComments);
            }
            //判断
            if (apCommentList.size() == 0) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "当前没有评论数据!");
            }
            long a1 = 1313;
            long b1 = 1314;
            long c = a1-b1;
            //截取集合中最新的5条评论数据
            List<CommentManagerVo> commentManagerVoList = apCommentList.stream().sorted((a, b) -> {
                return (int)b.getCreatedTime().getTime()-(int)a.getCreatedTime().getTime();
            }).map(newApComment -> {
                //查询当前回复的点赞量
                Query commentQuery = Query.query(Criteria.where("commentId").is(newApComment.getId()));
                List<ApCommentLike> apCommentLikes = mongoTemplate.find(commentQuery, ApCommentLike.class);
                //创建CommentManagerVo
                CommentManagerVo commentManagerVo = new CommentManagerVo();
                commentManagerVo.setDate(newApComment.getCreatedTime());
                commentManagerVo.setContent(newApComment.getContent());
                commentManagerVo.setReplies(null);
                commentManagerVo.setAdmireNum(apCommentLikes.size());  //评论的点赞量
                //查询当前评论的回复数据
                Query commentRepayQuery = Query.query(Criteria.where("commentId").is(newApComment.getId()));
                List<ApCommentRepay> apCommentRepays = mongoTemplate.find(commentRepayQuery, ApCommentRepay.class);
                if (apCommentRepays.size() > 0) {
                    //创建集合保存回复数据
                    ArrayList<CommentManagerRepVo> apCommentRepayList = new ArrayList<>();
                    for (ApCommentRepay apCommentRepay : apCommentRepays) {
                        //根据回复人id查询信息
                        ResponseResult<WmUser> wmUserResp2 = wemediaFeign.findByApUserId(apCommentRepay.getAuthorId() + "");
                        if (wmUserResp2.checkCode()) {
                            WmUser wmUser = wmUserResp2.getData();
                            //创建CommentManagerRepVo
                            CommentManagerRepVo commentManagerRepVo = new CommentManagerRepVo();
                            commentManagerRepVo.setNickName(wmUser.getName());
                            commentManagerRepVo.setContent(apCommentRepay.getContent());
                            apCommentRepayList.add(commentManagerRepVo);
                        }
                    }
                    //将apCommentRepayList放到commentManagerVo
                    commentManagerVo.setReplies(apCommentRepayList);
                    return commentManagerVo;
                }
                return null;
            }).filter(map->{
                return map!=null;
            }).collect(Collectors.toList());
            if(commentManagerVoList.size()>0){
                return ResponseResult.okResult(commentManagerVoList);
            }
        }
        return ResponseResult.okResult();
    }
}
